﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Office = Microsoft.Office.Core;

using System.Xml;
using System.Xml.Linq;
using System.IO;

namespace ETRoboConResultEditorExcel
{
    partial class EditorActionsPaneControl : UserControl
    {
        public EditorActionsPaneControl()
        {
            InitializeComponent();
        }

        private Dictionary<string, int> contestInfo = new Dictionary<string, int>();

        private void buttonGetGames_Click(object sender, EventArgs e)
        {
            comboBoxContestSelect.Items.Clear();
            comboBoxGameSpec.Items.Clear();
            contestInfo.Clear();
            gameSpecInfos.Clear();
            ETRoboConRM.ETRoboConRaceMgmtClient rm = new ETRoboConRM.ETRoboConRaceMgmtClient();
            //            using (var rm = new WSRaceMgmt.RaceMgmt())
            {
                //              WSRaceMgmt.ContestInfo[] infos;
                ETRoboConRM.ContestInfo[] infos;
                if (rm.GetContestInfo(out infos))
                {
                    foreach (var info in infos)
                    {
                        contestInfo.Add(info.Name, info.ContestId);
                        comboBoxContestSelect.Items.Add(info.Name);
                    }
                }
                //                WSRaceMgmt.GameSpecInfo[] gsInfos;
                ETRoboConRM.GameSpecInfo[] gsInfos;
                if (rm.GetGameSpecInfo(out gsInfos))
                {
                    foreach (var gsInfo in gsInfos)
                    {
                        gameSpecInfos.Add(gsInfo.Name, gsInfo.GameSpecId);
                        comboBoxGameSpec.Items.Add(gsInfo.Name);
                    }
                }
            }
            rm.Close();
        }

        private Dictionary<string, int> gameInfos = new Dictionary<string, int>();
        private Dictionary<string, int> gameSpecInfos = new Dictionary<string, int>();
        private Dictionary<string, string> areaOfGames = new Dictionary<string, string>();

        private void comboBoxContestSelect_SelectedIndexChanged(object sender, EventArgs e)
        {
            comboBoxGameSelect.Items.Clear();
            gameInfos.Clear();
            //gameSpecInfos.Clear();
            string contestName = (string)comboBoxContestSelect.SelectedItem;
            int contestId = contestInfo[contestName];
            var rm = new ETRoboConRM.ETRoboConRaceMgmtClient();
            //            using (var rm = new WSRaceMgmt.RaceMgmt())
            {
                //              WSRaceMgmt.GameInfo[] infos;
                ETRoboConRM.GameInfo[] infos;
                if (rm.GetGameInfo(out infos, contestId))
                {
                    comboBoxGameSelect.Items.Add("[Regist Game]");
                    foreach (var info in infos)
                    {
                        gameInfos.Add(info.Name, info.GameId);
                        areaOfGames.Add(info.Name, info.AreaName);
                        comboBoxGameSelect.Items.Add(info.Name);
                        
                    }
                }
                //    WSRaceMgmt.GameSpecInfo[] gsInfos;
                //    if (rm.GetGameSpecInfo(out gsInfos))
                //    {
                //        foreach (var gsInfo in gsInfos)
                //        {
                //            gameSpecInfos.Add(gsInfo.Name, gsInfo.GameSpecId);
                //            comboBoxGameSpec.Items.Add(gsInfo.Name);
                //        }
                //    }
            }
            rm.Close();
        }

        private void comboBoxGameSelect_SelectedIndexChanged(object sender, EventArgs e)
        {
            buttonShow.Enabled = true;
        }


        private void buttonShow_Click(object sender, EventArgs e)
        {
            Globals.Sheet1.StartShow();
            string game = comboBoxGameSelect.SelectedItem as string;
            string contest = comboBoxContestSelect.SelectedItem as string;
            Globals.Sheet2.SetGameInfo(contestInfo[contest], gameInfos[game]);

            Globals.Sheet2.ClearEntryTeamInfo();
            var entryTeamInfos = new Dictionary<int, ETRoboConRM.TeamInfo>();

            Globals.Sheet1.SetGameInfo(contest, game);

            ETRoboConRM.ETRoboConRaceMgmtClient rm = new ETRoboConRM.ETRoboConRaceMgmtClient();
//            using (var rm = new WSRaceMgmt.RaceMgmt())
            {
                ETRoboConRM.GameSpecInfo[] gameSpecInfo;
//                WSRaceMgmt.GameSpecInfo[] gameSpecInfo;
                rm.GetGameSpecInfo(out gameSpecInfo);
  //              WSRaceMgmt.TeamInfo[] teamInfos;
                ETRoboConRM.TeamInfo[] teamInfos;
                
                if (rm.GetEntryTeamInfo(out teamInfos, gameInfos[game]))//, out teamInfos))
                {
                    foreach (var teamInfo in teamInfos)
                    {
                        Globals.Sheet2.SetEntryTeamInfo(teamInfo.EntryTeamId, teamInfo.Bib, teamInfo.Name);
                        entryTeamInfos.Add(teamInfo.EntryTeamId, teamInfo);
                    }
                }

                SetTurnInfoInSheet2(game, rm, 1, entryTeamInfos);
                SetTurnInfoInSheet2(game, rm, 2, entryTeamInfos);
            }
            Globals.Sheet1.EndShow();
            buttonUpdate.Enabled = true;
        }

        private void SetTurnInfoInSheet2(string game, ETRoboConRM.ETRoboConRaceMgmtClient rm, int roundNo, Dictionary<int,ETRoboConRM.TeamInfo> entryTeamInfos)
        {
            ETRoboConRM.TurnInfo[] turnInfos;
//            WSRaceMgmt.TurnInfo[] turnInfos;
            if (rm.GetRaceOrder(out turnInfos,  gameInfos[game], roundNo))
            {
                if (roundNo == 1)
                {
                    Globals.Sheet1.TurnTotalNo = turnInfos.Length;
                }
                foreach (var turnInfo in turnInfos)
                {
                    Globals.Sheet2.SetTurnInfo(roundNo, turnInfo.No, turnInfo.TurnId);
                    if (turnInfo.InCourseRunnerId != -1)
                    {
                        ETRoboConRM.TeamInfo teamIn = entryTeamInfos[turnInfo.InCourseRunnerId];
                        SetTurnRunnerResult(rm, roundNo, turnInfo, teamIn, "IN");
                    }
                    //                    WSRaceMgmt.TeamInfo teamIn = entryTeamInfos[turnInfo.InCourceRunner];
                    if (turnInfo.OutCourseRunnerId != -1)
                    {
                        ETRoboConRM.TeamInfo teamOut = entryTeamInfos[turnInfo.OutCourseRunnerId];
                        SetTurnRunnerResult(rm, roundNo, turnInfo, teamOut, "OUT");
                    }
                    //                    WSRaceMgmt.TeamInfo teamOut = entryTeamInfos[turnInfo.OutCourceRunner];

                }
            }
        }

        private static void SetTurnRunnerResult(ETRoboConRM.ETRoboConRaceMgmtClient rm, int roundNo, ETRoboConRM.TurnInfo turnInfo, ETRoboConRM.TeamInfo teamInfo, string cource)
        {
            Globals.Sheet1.SetTurnInfo(roundNo, turnInfo.No, teamInfo.EntryTeamId, teamInfo.Bib, teamInfo.Name, cource);
           // WSRaceMgmt.RunnerStatus status;
            ETRoboConRM.RunnerStatus status;
            int? runTime;
            int? runPoint;
            string[] bonusResults;
            if (rm.GetTeamRaceResult(out status, out runTime,out runPoint,out                bonusResults,turnInfo.TurnId, teamInfo.EntryTeamId))
//                turnInfo.TurnId, teamInfo.EntryTeamId, out status, out runTime, out runPoint, out bonusResults))
            {
                Globals.Sheet1.SetRunnerResults(roundNo, turnInfo.No, teamInfo.EntryTeamId, status, runTime, runPoint, bonusResults);
            }
        }

        private void buttonUpdate_Click(object sender, EventArgs e)
        {
            ETRoboConRM.ETRoboConRaceMgmtClient rm = new ETRoboConRM.ETRoboConRaceMgmtClient();
//            using (var rm = new WSRaceMgmt.RaceMgmt())
            {
                foreach (int index in Globals.Sheet1.GetTurnRunnerIndex())
                {
                    int roundNo;
                    int turnNo;
                    string entryTeamId;
                    int runTime;
                    string cource;
                    string status;
                    string[] bonusResults;
                    Globals.Sheet1.GetTurnRunnerResults(index, out roundNo, out turnNo, out entryTeamId, out cource, out status, out runTime, out bonusResults);
                    int turnId;
                    if (Globals.Sheet2.GetTurnInfo(roundNo, turnNo, out turnId))
                    {
                        int? runPoint;
                        ETRoboConRM.RunnerStatus wsstatus = ETRoboConRM.RunnerStatus.UNKNOWN;
//                        WSRaceMgmt.RunnerStatus wsstatus = WSRaceMgmt.RunnerStatus.UNKNOWN;
                        if (status.CompareTo("READY") == 0)
                        {
                            wsstatus = ETRoboConRM.RunnerStatus.READY;// WSRaceMgmt.RunnerStatus.READY;
                        }
                        else if (status.CompareTo("COMPLETED") == 0)
                        {
                            wsstatus = ETRoboConRM.RunnerStatus.COMPLETED;// WSRaceMgmt.RunnerStatus.COMPLETED;
                        }
                        else if (status.CompareTo("RETIRED") == 0)
                        {
                            wsstatus = ETRoboConRM.RunnerStatus.RETIRED;// WSRaceMgmt.RunnerStatus.RETIRED;
                        }
                        else if (status.CompareTo("OBSTRUCTED") == 0)
                        {
                            wsstatus = ETRoboConRM.RunnerStatus.OBSTRUCTED;// WSRaceMgmt.RunnerStatus.OBSTRUCTED;
                        }
                        else if (status.CompareTo("DECLINED") == 0)
                        {
                            wsstatus = ETRoboConRM.RunnerStatus.DECLINED;// WSRaceMgmt.RunnerStatus.DECLINED;
                        }
                        if (!rm.UpdateTeamRaceResult(out runPoint, turnId, int.Parse(entryTeamId), wsstatus, (int?)runTime, bonusResults))
                        {
                            MessageBox.Show("TurnSetがありません。該当ラウンドを最低一回以上スタートしてください");
                            break;
                        }
//                            turnId, entryTeamId, wsstatus, (int?)runTime, bonusResults, out runPoint);
                        if (runPoint != null)
                        {
                            Globals.Sheet1.SetRunnerPoint(index, (int)runPoint);
                        }
                    }
                }
                rm.Close();
                Globals.Sheet1.ClearDurtiyStatus();
            }
        }

        private Dictionary<string,int> EntryTeamInfos = new Dictionary<string, int>();
        private void buttonShowResult_Click(object sender, EventArgs e)
        {
            if (comboBoxContestSelect.SelectedItem == null)
            {
                MessageBox.Show("Please select Game on the Editor Tab!");
                return;
            }
            ETRoboConRM.ETRoboConRaceMgmtClient rm = new ETRoboConRM.ETRoboConRaceMgmtClient();
            //            using (WSRaceMgmt.RaceMgmt rm = new WSRaceMgmt.RaceMgmt())
            {
                EntryTeamInfos.Clear();
                Globals.Sheet3.ClearTeamsResults();
                EntryTeamInfos.Clear();
                string game = comboBoxGameSelect.SelectedItem as string;
                ETRoboConRM.EntryTeamResultInfo[] results;
                //                WSRaceMgmt.EntryTeamResultInfo[] resutls;
                if (rm.GetEntryTeamResultInfos(out results, gameInfos[game], checkBoxCalc.Checked))
                {
                    foreach (var result in results)
                    {
                        int? rank = null;
                        if (result.Rank != null && result.Rank > 0)
                        {
                            rank = result.Rank;
                        }
                        double? modelPoint = null;
                        if (result.ModelPoint != null)
                        {
                            modelPoint = ((double)result.ModelPoint) / 100;
                        }
                        Globals.Sheet3.AddTeamResult(
                            result.Bib, result.TeamRegId, result.TeamName,
                            modelPoint, result.TotalRunPoint, result.TotalPoint, result.Rank);
                        EntryTeamInfos.Add(result.TeamName, result.EntryTeamId);
                    }
                    Globals.Sheet3.Activate();
                }

            }
            rm.Close();
        }

        private void buttonUpdateTotalResults_Click(object sender, EventArgs e)
        {
            int index = 0;
            int bib;
            string teamId;
            string name;
            int? runPoint;
            int? modelPoint;
            int? rank;
            ETRoboConRM.ETRoboConRaceMgmtClient rm = new ETRoboConRM.ETRoboConRaceMgmtClient();
//            using (WSRaceMgmt.RaceMgmt rm = new WSRaceMgmt.RaceMgmt())
            {
                string game = comboBoxGameSelect.SelectedItem as string;
                rm.ClearEntryTeamModelPoint(gameInfos[game]);
                while (Globals.Sheet3.GetTeamResult(out bib, out teamId, out name, out modelPoint, out runPoint, out rank,ref index) > 0)
                {
                    if (rank == 0)
                    {
                        rank = null;
                    }
                    rm.UpdateEntryTeamResultInfo(EntryTeamInfos[name], modelPoint, rank);
                }
            }
        }

        private void buttonEntryTeam_Click(object sender, EventArgs e)
        {
            if (comboBoxContestSelect.SelectedItem == null)
            {
                MessageBox.Show("Please select contest!");
                return;
            }
            string contestName = comboBoxContestSelect.SelectedItem as string;
            int contestId = contestInfo[contestName];

            int gameId = -1;
            bool gameExisted = false;
            if (comboBoxGameSelect.SelectedItem != null)
            {
                string selectedGame = comboBoxGameSelect.SelectedItem as string;
                if (gameInfos.TryGetValue(selectedGame, out gameId))
                {
                    gameExisted = true;
                }
            }

            if (!gameExisted)
            {
                string gameName = Globals.Sheet4.GetGameName();
                if (String.IsNullOrEmpty(gameName))
                {
                    MessageBox.Show("Please select game or specify in the sheet!");
                    return;
                }
                if (comboBoxGameSpec.SelectedItem == null)
                {
                    MessageBox.Show("Please select GameSpec!");
                    return;
                }
                string gameSpecName = comboBoxGameSpec.SelectedItem as string;
                int gameSpecId = gameSpecInfos[gameSpecName];
                var rm = new ETRoboConRM.ETRoboConRaceMgmtClient();
//                using (WSRaceMgmt.RaceMgmt rm = new WSRaceMgmt.RaceMgmt())
                {
                    if (!rm.RegistNewGame(out gameId,contestId,gameSpecId,gameName))
                    {
                        MessageBox.Show("Game Registration Failed!");
                        return;
                    }
                    gameExisted = true;
                }
                rm.Close();
            }
            if (gameExisted)
            {
                
                string areaName = Globals.Sheet4.GetAreaName();
                EntryTeamRegistration(ref contestId, ref gameId, areaName);
            }
        }

        private static void EntryTeamRegistration(ref int contestId, ref int gameId, string areaName)
        {
            var rm = new ETRoboConRM.ETRoboConRaceMgmtClient();
//            using (WSRaceMgmt.RaceMgmt rm = new WSRaceMgmt.RaceMgmt())
            {
                rm.ClearGameRound(gameId);
                Dictionary<string, int> teamInfos = new Dictionary<string, int>();
                EntryTurnInfo[] etInfos = Globals.Sheet4.GetEntryTurnInfos();
                foreach (var etInfo in etInfos)
                {
                    int teamId;
                    if (!string.IsNullOrEmpty(etInfo.ICTeamName))
                    {
                        if (etInfo.ICTeamName.EndsWith(@"*"))
                        {
                            etInfo.IsICExhibition = true;
                            etInfo.ICTeamName = etInfo.ICTeamName.Substring(0, etInfo.ICTeamName.Length - 1);
                        }
                        else
                        {
                            etInfo.IsICExhibition = false;
                        }
                        if (rm.RegistTeam(out teamId, contestId, areaName, etInfo.ICTeamName, "Unknown", etInfo.ICIdOfTeam, etInfo.ICRegIdOfTeam))
                        {
                            int etId;
                            if (etInfo.ICBib != null && rm.RegistEntryTeam(out etId, gameId, teamId, (int)etInfo.ICBib, (bool)etInfo.IsICExhibition))
                            {
                                teamInfos.Add(etInfo.ICTeamName, etId);
                            }
                        }
                    }
                    if (!string.IsNullOrEmpty(etInfo.OCTeamName))
                    {
                        if (etInfo.OCTeamName.EndsWith(@"*"))
                        {
                            etInfo.IsOCExhibition = true;
                            etInfo.OCTeamName = etInfo.OCTeamName.Substring(0, etInfo.OCTeamName.Length - 1);
                        }
                        else
                        {
                            etInfo.IsOCExhibition = false;
                        }
                        if (rm.RegistTeam(out teamId, contestId, areaName, etInfo.OCTeamName, "Unknown", etInfo.OCIdOfTeam, etInfo.OCRegIdOfTeam))
                        {
                            int etId;
                            if (etInfo.OCBib != null && rm.RegistEntryTeam(out etId, gameId, teamId, (int)etInfo.OCBib, (bool)etInfo.IsOCExhibition))
                            {
                                teamInfos.Add(etInfo.OCTeamName, etId);
                            }
                        }
                    }
                }
                int roundId;
                if (rm.RegistRound(out roundId, gameId,1))
                {
                    foreach (EntryTurnInfo etInfo in etInfos)
                    {
                        int icET = -1;
                        if (etInfo.ICBib != null)
                        {
                            icET = teamInfos[etInfo.ICTeamName];
                        }
                        int ocET = -1;
                        if (etInfo.OCBib != null)
                        {
                            ocET = teamInfos[etInfo.OCTeamName];
                        }
                        int turnId;
                        if (rm.RegistTurn(out turnId, roundId, icET, ocET))
                        {
                        }
                    }
                    int round2Id;
                    if (!rm.RegistRound2AllTurnsByAuto(out round2Id, gameId, roundId))
                    {
                        MessageBox.Show("Round 2 Registration Failed");
                    }
                }
                else
                {
                    MessageBox.Show("Round1 Registration Failed");
                }
            }
            rm.Close();
        }


        private void buttonFixTurnRunner_Click(object sender, EventArgs e)
        {
            if (comboBoxGameSelect.SelectedItem != null)
            {
                string gameName = comboBoxGameSelect.SelectedItem as string;
                var rm = new ETRoboConRM.ETRoboConRaceMgmtClient();
                //using (WSRaceMgmt.RaceMgmt rm = new WSRaceMgmt.RaceMgmt())
                {
                    rm.FixTurnRunner(gameInfos[gameName]);
                }
                rm.Close();
            }
        }

        private void buttonClearEntryInfo_Click(object sender, EventArgs e)
        {
            if (comboBoxGameSelect.SelectedItem != null)
            {
                string gameName = comboBoxGameSelect.SelectedItem as string;
                var rm = new ETRoboConRM.ETRoboConRaceMgmtClient();
//                using (WSRaceMgmt.RaceMgmt rm = new WSRaceMgmt.RaceMgmt())
                {
                    rm.ClearGameInfo(gameInfos[gameName]);
                }
            }
        }

        private void checkBoxCourceReverse_CheckedChanged(object sender, EventArgs e)
        {
            Globals.Sheet4.ReverseCource();
        }

        private void checkBoxExhibitionEnable_CheckedChanged(object sender, EventArgs e)
        {
//            Globals.Sheet4.GetExhibitionMarkColor();
        }

        private void buttonGetGameSpec_Click(object sender, EventArgs e)
        {
            var client = new ETRoboConRM.ETRoboConRaceMgmtClient();
//            using (WSRaceMgmt.RaceMgmt client = new ETRoboConResultEditorExcel.WSRaceMgmt.RaceMgmt())
            {
  //              WSRaceMgmt.GameSpecInfo[] infos;
                ETRoboConRM.GameSpecInfo[] infos;
                if (client.GetGameSpecInfo(out infos))
                {
                    comboBoxGameSpecForGameSpec.Items.Clear();
                    foreach (var info in infos)
                    {
                        comboBoxGameSpecForGameSpec.Items.Add(info.Name + ";" + info.GameSpecId);
                    }
                }
            }
            client.Close();
        }

        private void comboBoxGameSpecForGameSpec_SelectedIndexChanged(object sender, EventArgs e)
        {
        }

        private void buttonClearGameSpec_Click(object sender, EventArgs e)
        {
            GameSpecInfo gsInfo = Globals.Sheet5.GetGameSpecInfo();
            if (!String.IsNullOrEmpty(gsInfo.Name))
            {
                var client = new ETRoboConRM.ETRoboConRaceMgmtClient();
//                using (WSRaceMgmt.RaceMgmt client = new WSRaceMgmt.RaceMgmt())
                {
                    if (client.ClearGameSpecInfo(gsInfo.Name))
                    {
                    }
                }
                client.Close();
            }
        }

        private void buttonUpdateGameSpec_Click(object sender, EventArgs e)
        {
            GameSpecInfo gsInfo = Globals.Sheet5.GetGameSpecInfo();
            if (!String.IsNullOrEmpty(gsInfo.Name))
            {
                var client = new ETRoboConRM.ETRoboConRaceMgmtClient();
                //                using (WSRaceMgmt.RaceMgmt client = new WSRaceMgmt.RaceMgmt())
                {
                    ETRoboConRM.CourseName courseName = ETRoboConRM.CourseName.IN;
                    //                    WSRaceMgmt.CourceName courseName = WSRaceMgmt.CourceName.IN;
                    if (gsInfo.CourceName.CompareTo(courseName.ToString()) != 0)
                    {
                        //                        courseName = WSRaceMgmt.CourceName.OUT;
                        courseName = ETRoboConRM.CourseName.OUT;
                    }
                    ETRoboConRM.GameSpecInfo rmGSInfo = client.FindGameSpec(gsInfo.Name);

                    //                    WSRaceMgmt.GameSpecInfo rmGSInfo = client.FindGameSpec(gsInfo.Name);
                    if (rmGSInfo == null)
                    {
                        int gsId;
                        if (client.RegistGameSpec(out gsId, gsInfo.Name, gsInfo.Memo))
                        {
                            gsInfo.Id = gsId.ToString();
                            Globals.Sheet5.SetGameSpecInfo(gsInfo);
                        }
                    }
                    else
                    {
                        if (client.ClearBonusSpecs(gsInfo.Name, courseName))
                        {
                        }
                    }
                    if (rmGSInfo != null)
                    {
                        rmGSInfo = client.FindGameSpec(gsInfo.Name);
                        client.UpdaetGameSpecInfo(rmGSInfo.GameSpecId, gsInfo.Name, gsInfo.Memo);

                        gsInfo.Id = rmGSInfo.GameSpecId.ToString();
                        Globals.Sheet5.SetGameSpecInfo(gsInfo);

                        BonusSpecInfo[] bsInfos = Globals.Sheet5.GetBonusSpecInfo();
                        foreach (var bsInfo in bsInfos)
                        {
                            int clearOrder;
                            int bsId = -1;
                            if (client.AppendBonusSpec(out clearOrder, out bsId, int.Parse(gsInfo.Id), courseName, bsInfo.Name, bsInfo.ShorName, bsInfo.Specification, bsInfo.Point))
                            {
                                bsInfo.Id = bsId.ToString();
                                bsInfo.ClearOrder = clearOrder;
                            }

                        }
                        Globals.Sheet5.SetBonusSpecInfo(bsInfos);
                    }
                }
                client.Close();
            }
        }

        private void comboBoxCourceNameForGameSpec_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBoxGameSpecForGameSpec.SelectedItem == null)
            {
                MessageBox.Show("Please select GameSpec");
                return;
            }
            string[] selectedItem = comboBoxGameSpecForGameSpec.SelectedItem.ToString().Split(new char[] { ';' });
            string id = selectedItem[1];
            string name = selectedItem[0];

            var client = new ETRoboConRM.ETRoboConRaceMgmtClient();
//            using (WSRaceMgmt.RaceMgmt client = new ETRoboConResultEditorExcel.WSRaceMgmt.RaceMgmt())
            {
                ETRoboConRM.BonusSpecInfo[] infos;
                ETRoboConRM.CourseName course = ETRoboConRM.CourseName.IN;
//                WSRaceMgmt.BonusSpecInfo[] infos;
  //              WSRaceMgmt.CourceName cource = WSRaceMgmt.CourceName.IN;
                string selectedCource = comboBoxCourceNameForGameSpec.SelectedItem.ToString();
                if (selectedCource.CompareTo(course.ToString()) == 0)
                {
//                    cource = WSRaceMgmt.CourceName.IN;
                    course = ETRoboConRM.CourseName.IN;
                }
                else
                {
//                    cource = WSRaceMgmt.CourceName.OUT;
                    course = ETRoboConRM.CourseName.OUT;
                }
               // WSRaceMgmt.GameSpecInfo
                 var   gsInfo = client.FindGameSpec(name);
                if (gsInfo != null)
                {
                    Globals.Sheet5.SetGameSpecInfo(new GameSpecInfo { Id = gsInfo.GameSpecId.ToString(), Name = gsInfo.Name, Memo = gsInfo.Memo, CourceName = course.ToString() });
                    if (client.GetGameCourseBonusSpecInfo(out infos, int.Parse(id), course))
                    {
                        List<BonusSpecInfo> bsInfos = new List<BonusSpecInfo>();
                        foreach (var info in infos)
                        {
                            bsInfos.Add(new BonusSpecInfo { Id = info.BonusSpecId.ToString(), Name = info.Name, ShorName = info.ShortName, Specification = info.Specification, Point = info.Point, ClearOrder = info.ClearOrder });
                        }
                        Globals.Sheet5.SetBonusSpecInfo(bsInfos.ToArray());
                    }
                }
            }

        }

        private void buttonUpdateContestInfo_Click(object sender, EventArgs e)
        {
            var client = new ETRoboConRM.ETRoboConRaceMgmtClient();
//            using (WSRaceMgmt.RaceMgmt client = new WSRaceMgmt.RaceMgmt())
            {
                ETRoboConResultEditorExcel.ContestInfo info =
                Globals.Sheet6.GetContestInfo();
                if (info != null)
                {
  //                  Guid id = new Guid();
    //                if (String.IsNullOrEmpty(info.ID))
      //              {
        //                if (MessageBox.Show(@"コンテストのIDを自動的に割り当てますか?", @"確認", MessageBoxButtons.YesNo) == DialogResult.No)
          //              {
            //                return;
              //          }
                //        id = Guid.NewGuid();
                  //  } else{
                    //    id = new Guid(info.ID);
                 //   }
                    int contestId=-1;
                    if (client.RegistContest(out contestId,info.Name,info.Memo,info.Year))
               //     Guid resultId = client.RegistContest(id, info.Name, info.Memo, info.Year);

                    info.ID = contestId.ToString();
                    Globals.Sheet6.SetContestInfo(info);
                }
            }
            client.Close();
        }

        private void buttonContestInfo_Click(object sender, EventArgs e)
        {
            if (comboBoxContestSelect.SelectedItem == null)
            {
                MessageBox.Show(@"Contestで選択を!!");
                return;
            }
            int id = contestInfo[comboBoxContestSelect.SelectedItem.ToString()];
            var client = new ETRoboConRM.ETRoboConRaceMgmtClient();
//            using (WSRaceMgmt.RaceMgmt client = new WSRaceMgmt.RaceMgmt())
            {
                int year;
                string name;
                string memo;
                if (client.GetContestById(out year,out name,out memo,id)){
                    Globals.Sheet6.SetContestInfo(new ContestInfo { ID = id.ToString(), Year = year, Name = name, Memo = memo });
                }
            }
            client.Close();
        }

        private void buttonOpenGSDefFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.DefaultExt = "xml";
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                textBoxGameSpecDefFileName.Text = dialog.FileName;
            }
            if (File.Exists(textBoxGameSpecDefFileName.Text))
            {
                XmlReader reader = XmlReader.Create(new FileStream(textBoxGameSpecDefFileName.Text, FileMode.Open, FileAccess.Read));
                XDocument xdoc = XDocument.Load(reader);
                var gameSpecs = xdoc.Elements("Contests").First().Elements("GameSpecs").First().Elements("GameSpec");
                comboBoxGameSpecName.Items.Clear();
                foreach (var gs in gameSpecs)
                {
                    comboBoxGameSpecName.Items.Add(gs.Attribute("Name").Value);
                }
            }
        }

        private void buttonLoadGameSpecXML_Click(object sender, EventArgs e)
        {
            if (File.Exists(textBoxGameSpecDefFileName.Text))
            {
                var rm = new ETRoboConRM.ETRoboConRaceMgmtClient();
//                using (WSRaceMgmt.RaceMgmt rm = new WSRaceMgmt.RaceMgmt())
                {
                    FileStream fs = new FileStream(textBoxGameSpecDefFileName.Text, FileMode.Open, FileAccess.Read);
                    TextReader reader = new StreamReader(fs);
                    string xmlDefinition = reader.ReadToEnd();
//                    rm.LoadGameSpec(textBoxGameSpecNameForLoad.Text, xmlDefinition);
                    string selectedName = comboBoxGameSpecName.SelectedItem as string;
                    rm.LoadGameSpec(selectedName, xmlDefinition);

                    fs.Seek(0, SeekOrigin.Begin);
                    XmlReader xreader = XmlReader.Create(fs);
                    XDocument xdoc = XDocument.Load(xreader);
                    var contests = xdoc.Elements("Contests").First().Elements("Contest");
                    if (contests.Count() == 1)
                    {
                        var contest = contests.First();
                        int contestId = -1;
                        rm.RegistContest(out contestId, contest.Attribute("Name").Value, "", System.Convert.ToInt32(contest.Attribute("Year").Value));
//                            new Guid(contest.Attribute("Id").Value), contest.Attribute("Name").Value, "", System.Convert.ToInt32(contest.Attribute("Year").Value));
                    }
                }
                rm.Close();
            }
        }

        private void buttonOpenFileDialogTeamInfoDefFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.DefaultExt = "xml";
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                textBoxTeamInfoDefFileName.Text = dialog.FileName;
            }
        }

        private void buttonUploadTeamInfo_Click(object sender, EventArgs e)
        {
            if (File.Exists(textBoxTeamInfoDefFileName.Text))
            {
                var rm = new ETRoboConRM.ETRoboConRaceMgmtClient();
//                using (WSRaceMgmt.RaceMgmt rm = new WSRaceMgmt.RaceMgmt())
                {
                    FileStream fs = new FileStream(textBoxTeamInfoDefFileName.Text, FileMode.Open, FileAccess.Read);
                    TextReader reader = new StreamReader(fs);
                    string xmlDefinition = reader.ReadToEnd();
                    rm.LoadTeamInfo( textBoxContestNameForTeamInfo.Text, xmlDefinition);
                }
                rm.Close();
            }
        }

        private void buttonOpenFileDialogForContestAndTeams_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.DefaultExt = "xml";
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                textBoxContestName.Text = dialog.FileName;
            }
            if (File.Exists(textBoxContestName.Text))
            {
                XmlReader reader = XmlReader.Create(new FileStream(textBoxContestName.Text, FileMode.Open, FileAccess.Read));
                XDocument xdoc = XDocument.Load(reader);
                var contests = xdoc.Elements("Contests").First().Elements("Contest");
                comboBoxContestForTeamRegist.Items.Clear();
                foreach (var contest in contests)
                {
                    comboBoxContestForTeamRegist.Items.Add(contest.Attribute("Name").Value);

                }
            }
        }

        private void buttonLoadTeamInfo_Click(object sender, EventArgs e)
        {
            if (comboBoxContestForTeamRegist.SelectedItem == null || comboBoxDivisionForTeamRegist.SelectedItem == null)
            {
                MessageBox.Show("Please select contest and division!");
                return;
            }
            var rm = new ETRoboConRM.ETRoboConRaceMgmtClient();
            //            using (WSRaceMgmt.RaceMgmt rm = new WSRaceMgmt.RaceMgmt())
            {
                if (File.Exists(textBoxContestName.Text))
                {
                    FileStream fs = new FileStream(textBoxContestName.Text, FileMode.Open, FileAccess.Read);
                    TextReader reader = new StreamReader(fs);
                    string definition = reader.ReadToEnd();
                    if (rm.LoadTeamInfo(comboBoxContestForTeamRegist.SelectedItem.ToString(), definition))
                    {
                        XmlReader xreader = XmlReader.Create(new StringReader(definition));
                        XDocument xdoc = XDocument.Load(xreader);
                        foreach (var contest in xdoc.Elements("Contests").First().Elements("Contest"))
                        {
                            if (contest.Attribute("Name").Value.CompareTo(comboBoxContestForTeamRegist.SelectedItem.ToString()) == 0)
                            {
                                var teams = from t in contest.Elements("Teams").First().Elements("Team")
                                            where t.Attribute("Division").Value.Contains(comboBoxDivisionForTeamRegist.SelectedItem.ToString())
                                            select t;
                                if (checkBoxAssignTurnAuto.Checked)
                                {
                                    System.Random rand = new Random(System.DateTime.Now.Millisecond);
                                    List<int> orderMark = new List<int>();
                                    for (int i = 0; i < teams.Count(); i++)
                                    {
                                        orderMark.Add(i);
                                    }
                                    //                                    List<WSRaceMgmt.TeamInfo> teamOrder = new List<WSRaceMgmt.TeamInfo>();
                                    var teamOrder = new List<ETRoboConRM.TeamInfo>();
                                    int bib = 1;
                                    while (orderMark.Count() > 0)
                                    {
                                        int index = (int)(orderMark.Count * rand.NextDouble());
                                        teamOrder.Add(new ETRoboConRM.TeamInfo
                                        {
                                            Bib = bib++,
                                            Name = teams.ElementAt(orderMark.ElementAt(index)).Attribute("Name").Value,
                                            Id = teams.ElementAt(orderMark.ElementAt(index)).Attribute("Id").Value
                                        });
                                        orderMark.RemoveAt(index);
                                    }
                                    var bibOrderedTeams = from t in teamOrder
                                                          orderby t.Bib
                                                          select t;
                                    // Show teams in Excel sheet
                                    for (int i = 0; i < bibOrderedTeams.Count(); i += 2)
                                    {
                                        var teamIn = bibOrderedTeams.ElementAt(i);
                                        Globals.Sheet4.SetTeamInfo(teamIn.Id, teamIn.Bib.ToString(), teamIn.Name, (i / 2) + 1, Sheet4.Side.Left);
                                        if (i < bibOrderedTeams.Count() - 1)
                                        {
                                            var teamOut = bibOrderedTeams.ElementAt(i + 1);
                                            Globals.Sheet4.SetTeamInfo(teamOut.Id, teamOut.Bib.ToString(), teamOut.Name, (i / 2) + 1, Sheet4.Side.Right);
                                        }
                                    }
                                }
                                else
                                {
                                    int index = 0;
                                    while (index < teams.Count())
                                    {
                                        Sheet4.Side currentSide = Sheet4.Side.Left;
                                        if ((index % 2) != 0)
                                        {
                                            currentSide = Sheet4.Side.Right;
                                        }
                                        int turn = (index) / 2 + 1;
                                        var team = teams.ElementAt(index);
                                        Globals.Sheet4.SetTeamInfo(team.Attribute("Id").Value, "", team.Attribute("Name").Value, turn, currentSide);
                                        index++;
                                    }

                                }
                            }
                        }
                    }
                }
            }
            rm.Close();
        }

        private void buttonGetEntryTeams_Click(object sender, EventArgs e)
        {
            if (comboBoxContestSelect.SelectedItem == null || comboBoxGameSelect.SelectedItem == null)
            {
                MessageBox.Show("Please Select Contest and Game!");
                return;
            }
            var rm = new ETRoboConRM.ETRoboConRaceMgmtClient();
//            using (WSRaceMgmt.RaceMgmt rm = new ETRoboConResultEditorExcel.WSRaceMgmt.RaceMgmt())
            {
                int roundNo = 1;
                string selectedContest = comboBoxContestSelect.SelectedItem as string;
                string selectedGame = comboBoxGameSelect.SelectedItem as string;
                int contestId = contestInfo[selectedContest];
                int gameId = gameInfos[selectedGame];
                ETRoboConRM.TeamInfo[] infos;
//                WSRaceMgmt.TeamInfo[] infos;
                if (rm.GetEntryTeamInfo( out infos, gameId))
                {
                    Globals.Sheet4.SetGameName(selectedGame);
                    Globals.Sheet4.SetRoundNo(1);
                    Globals.Sheet4.SetTurnNo((infos.Count() + 1) / 2);
                    Globals.Sheet4.SetAreaName(areaOfGames[selectedGame]);

                    foreach (var et in infos)
                    {
                        int etId;
                        int turnNo;
                        ETRoboConRM.CourseName course;
//                        WSRaceMgmt.CourceName course;
                        if (rm.GetTurnInfoOfTeam(out etId, out turnNo, out course, gameId,et.Id, et.RegId, roundNo))
                        {
                            Sheet4.Side side;
                            if (course == ETRoboConRM.CourseName.IN)
                            {
                                side = Sheet4.Side.Left;
                            }
                            else
                            {
                                side = Sheet4.Side.Right;
                            }
                            if (checkBoxCourceReverse.Checked)
                            {
                                if (side == Sheet4.Side.Left)
                                {
                                    side = Sheet4.Side.Right;
                                }
                                else
                                {
                                    side = Sheet4.Side.Left;
                                }
                            }
                            Globals.Sheet4.SetTeamInfo(et.RegId.ToString(), et.Bib.ToString(), et.Name, turnNo, side);
                        }
                    }
                }


            }
        }

        private void buttonReverseResult_Click(object sender, EventArgs e)
        {
            if (checkBoxReverseRound1.Checked)
            {
                Globals.Sheet1.ReverseResultEditing(1);
            }
            if (checkBoxReverseRound2.Checked)
            {
                Globals.Sheet1.ReverseResultEditing(2);
            }
        }

        private void buttonAnalysisShow_Click(object sender, EventArgs e)
        {
            if (comboBoxGameSelect.SelectedItem == null)
            {
                MessageBox.Show("Please select Game!");
                return;
            }
            string game = comboBoxGameSelect.SelectedItem as string;
            int gameId = -1;
            bool gameExisted = false;
            if (comboBoxGameSelect.SelectedItem != null)
            {
                string selectedGame = comboBoxGameSelect.SelectedItem as string;
                if (gameInfos.TryGetValue(selectedGame, out gameId))
                {
                    gameExisted = true;
                }
            }
            if (gameExisted)
            {
                ETRoboConRM.ETRoboConRaceMgmtClient rm = new ETRoboConRM.ETRoboConRaceMgmtClient();
                //            using (WSRaceMgmt.RaceMgmt rm = new WSRaceMgmt.RaceMgmt())
                {
                    ETRoboConRM.TeamTotalResult[] results;
                    if (rm.GetTeamTotalResults(out results, gameId))
                    {
                        Globals.Sheet7.UpdateResultInfo(results);
                    }
                }
            }
        }

        private void buttonEditRearrange_Click(object sender, EventArgs e)
        {
            int bib = 1;
            int index = 1;
            string course;
            string name;
            int runTime;
            string[] bonus;
            while (true){
                course="IN";
                if (!Globals.Sheet1.GetTeamResult(bib, course, out name, out runTime, out bonus))
                {
                    break;
                }
                Globals.Sheet9.WriteTeamResult(index, bib, name, course, runTime, bonus);
                course = "OUT";
                if (!Globals.Sheet1.GetTeamResult(bib, course, out name, out runTime, out bonus))
                {
                    break;
                }
                Globals.Sheet9.WriteTeamResult(index, bib, name, course, runTime, bonus);
                index++;
                bib++;
            }
        }

        private void buttonModelResultCopyUpdate_Click(object sender, EventArgs e)
        {
            if (comboBoxContestSelect.SelectedItem == null)
            {
                MessageBox.Show("Please select Game!");
                return;
            }
            int index = 0;
            int bib;
            string teamId;
            string name;
            double? modelPoint;
            ETRoboConRM.ETRoboConRaceMgmtClient rm = new ETRoboConRM.ETRoboConRaceMgmtClient();
            string game = comboBoxGameSelect.SelectedItem as string;
            rm.ClearEntryTeamModelPoint(gameInfos[game]);
            while (Globals.Sheet8.GetTeamModelPoint(out teamId, out bib, out name, out modelPoint, ref index) >= 0)
            {
                if (modelPoint != null)
                {
                    int mp = (int)(System.Math.Round(modelPoint.Value * 100));
                    int teamIdInt = int.Parse(teamId);
                    if (!rm.UpdateEntryTeamModelPoint(teamIdInt, mp))
                    {
                        MessageBox.Show("The Team Id may not exist!");
                    }
                }
            }
        }

        private void buttonModelResultCopyShow_Click(object sender, EventArgs e)
        {
            if (comboBoxContestSelect.SelectedItem == null)
            {
                MessageBox.Show("Please select Game!");
                return;
            }
            ETRoboConRM.ETRoboConRaceMgmtClient rm = new ETRoboConRM.ETRoboConRaceMgmtClient();
            EntryTeamInfos.Clear();
            string game = comboBoxGameSelect.SelectedItem as string;
            ETRoboConRM.EntryTeamResultInfo[] results;
            if (rm.GetEntryTeamResultInfos(out results, gameInfos[game], checkBoxCalc.Checked))
            {
                int index=0;
                foreach (var result in results)
                {
                    double? modelPoint = null;
                    if (result.ModelPoint != null)
                    {
                        modelPoint = ((double)result.ModelPoint) / 100;
                    }
                    index = Globals.Sheet8.AddTeamModelPoint(result.TeamRegId.ToString(), result.Bib, result.TeamName, modelPoint, index);
                    EntryTeamInfos.Add(result.TeamName, result.EntryTeamId);
                }
                Globals.Sheet8.Activate();
            }


        }

    }
}
